package flux;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class GestionFlux {

	private String pathFichierStockage;
	private List<Flux> listeFlux;


	public GestionFlux(String path) {
		this.pathFichierStockage = path;
		this.listeFlux = new ArrayList<Flux>();
		this.initialisation();
	}


	public String getPathFichierStockage() {
		return pathFichierStockage;
	}


	public void setPathFichierStockage(String path) {
		this.pathFichierStockage = path;
	}


	public List<Flux> getListeFlux() {
		return listeFlux;
	}


	
	
	public void sauve(){
		PrintWriter sortie;
		try{
			FileWriter fw = new FileWriter(this.pathFichierStockage);
			BufferedWriter output = new BufferedWriter(fw);
			for(int i=0;i<listeFlux.size();i++){ 
				output.write(listeFlux.get(i).getUrlFlux());
				output.write("\n");
			}
			output.flush();
			output.close();
		} 
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	
	public void initialisation(){
		String chaine="";
		try{
			InputStream ips=new FileInputStream(this.pathFichierStockage); 
			InputStreamReader ipsr=new InputStreamReader(ips);
			BufferedReader br=new BufferedReader(ipsr);
			String ligne;
			String str[];
			while ((ligne=br.readLine())!=null){
				//str = ligne.split("=");
				listeFlux.add(new Flux(ligne));
			}
			br.close(); 
		}
		catch(Exception e){
			e.printStackTrace();
		}

	}
	
	public Flux getFlux(String chemin){
		for(int i=0; i<this.listeFlux.size(); i++){
			if(this.listeFlux.get(i).getUrlFlux().equals(chemin)){
				return this.listeFlux.get(i);
			}
		}
		return null;
	}
	

	public void setListeFlux(List<Flux> listeFlux) {
		this.listeFlux = listeFlux;
	}
	
	public void ajouterFlux(String url){
		this.listeFlux.add(new Flux(url));
		this.sauve();
	}
	
	public void modifierFlux(String url, int index){
		this.listeFlux.get(index).setUrlFlux(url);
		this.sauve();
	}
	
	public void supprimerFlux(int index){
		this.listeFlux.remove(index);
		this.sauve();
	}
}
